/*
 *   Copyright 2021 zzh
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.aduib.boot.common.json;

import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @description: NullSerializerModifier
 * @author: zzh
 * @date: 2021/9/30 13:51
 */
public class NullSerializerModifier extends BeanSerializerModifier {

  private final JsonSerializer<Object> nullArrayJsonSerializer = new NullArrayJsonSerializer();

  private final JsonSerializer<Object> nullMapJsonSerializer = new NullMapJsonSerializer();

  private final JsonSerializer<Object> nullStringJsonSerializer = new NullStringJsonSerializer();

  @Override
  public List<BeanPropertyWriter> changeProperties(
      SerializationConfig config,
      BeanDescription beanDesc,
      List<BeanPropertyWriter> beanProperties) {
    for (BeanPropertyWriter writer : beanProperties) {
      if (isStringType(writer) || isNumberType(writer)) {
        writer.assignNullSerializer(this.nullStringJsonSerializer);
      }
      if (isArrayType(writer)) {
        writer.assignNullSerializer(this.nullArrayJsonSerializer);
      }
      if (isMapType(writer)) {
        writer.assignNullSerializer(this.nullMapJsonSerializer);
      }
    }
    return beanProperties;
  }

  private boolean isMapType(BeanPropertyWriter writer) {
    return Map.class.isAssignableFrom(writer.getType().getRawClass());
  }

  private boolean isArrayType(BeanPropertyWriter writer) {
    Class<?> clazz = writer.getType().getRawClass();
    return clazz.isArray() || Collection.class.isAssignableFrom(clazz);
  }

  private boolean isStringType(BeanPropertyWriter writer) {
    return String.class.isAssignableFrom(writer.getType().getRawClass());
  }

  private boolean isNumberType(BeanPropertyWriter writer) {
    return Number.class.isAssignableFrom(writer.getType().getRawClass());
  }
}
